<script setup>
import { ref, reactive, onMounted, watch, nextTick, h } from 'vue';
import { space2userApi as MainApi, space2userById as MainById, iuserApi, iuserById } from '@T2/service/api.ts';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useCurrentWatchStore, useIuserInfoStore } from '@T2/store/users.ts';
import { isPhone } from '@T2/utils/utils.ts';
import { Md5 } from 'ts-md5';

const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;
const iuserInfoStore = useIuserInfoStore();
const { info } = iuserInfoStore;

const { space, space_name } = defineProps({
  space: {
    type: Number,
    required: true,
  },
  space_name: {
    type: String,
    default: '',
  }
});
const emits = defineEmits(['closed']);
// 19933338976
onMounted(() => {
  GetMainTable();
});
const MainTable = reactive({
  data: [],
  total: 0,
});
const Filter = reactive({
  page: 1,
  // pagesize: 30,
  search: '',
});
watch(() => ({...Filter}), (nv, ov) => {
  if (nv.page === 1 || nv.page !== ov.page) {
    GetMainTable();
  } else {
    Filter.page = 1;
  }
});
const GetMainTable = () => {
  MainApi({
    method: 'get',
    params: {
      ...Filter,
      ordering: 'create_time',
      space: space,
    }
  }).then(res => {
    MainTable.data = res?.results || [];
    MainTable.total = res?.count || 0;
  });
}

/* 新增编辑 */
const MainPopup = reactive({
  visible: false,
  type: '新增',
  loading: false,
});
const MainForm = reactive({
  model: {},
  iuserList: [],
  iuserMore: false,
});
const remoteUserMethod = (inp) => {
  iuserRt.contract = inp;
  if (!inp) {
    return;
  }
  iuserApi({
    method: 'get',
    params: {
      page: 1,
      pagesize: 5,
      search: inp,
    },
  }).then(res => {
    const { results, count } = res;
    MainForm.iuserList = results || [];
    MainForm.iuserMore = count !=  MainForm.iuserList.length;
  });
}
const MainFormRef = ref(null);
const handleMainAdd = () => {
  MainPopup.visible = true;
  MainPopup.type = '新增';
  MainForm.model = {
    user_gender: '男',
    user_identity: '家属',
  };
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}
const handleMainEdit = (row) => {
  MainPopup.visible = true;
  MainPopup.type = '编辑';
  MainForm.model = {
    id: row.id,
    user: row.user,
    user_truename: row.user_truename,
    user_gender: row.user_gender,
    user_identity_code: row.user_identity_code,
    user_identity: row.user_identity,
  };
  iuserRt.type = '编辑';
  iuserRt.model = {
    id: row.user,
    contract: row.user_contract,
    truename: row.user_truename,
    gender: row.user_gender,
    identity_code: row.user_identity_code,
    identity: row.user_identity,
  }
  remoteUserMethod(row.user_contract);
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}
const handleMainDelete = (row) => {
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, `您是否要删除该用户？`),
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
    MainById({
      method: 'delete',
      id: row.id,
    }).then(res => {
      ElMessage.success('删除成功');
      GetMainTable();
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}
const handleMainSubmit = async () => {
  try {
    MainPopup.loading = true;
  if (!iuserRt.type) {
    await MainFormRef.value.validate();
    MainPopup.loading = false;
    return;
  }
  const valid1 = await MainFormRef.value.validate(valid => valid);
  const valid2 = await iuserRtRef.value.validate(valid => valid);
  if (!valid1 || !valid2) {
    MainPopup.loading = false;
    return;
  }
  if (!isPhone(iuserRt.model.contract)) {
    ElMessage.error('请输入正确的手机号');
    MainPopup.loading = false;
    return;
  }
  submitApi();
  } catch (error) {
    MainPopup.loading = false;
  }
}
const submitApi = async () => {
  let response = null;
  const { id, contract, ...iuserOthers } = iuserRt.model;
  if (!id) {
    /* 新增用户 */
    let auth_user_w = {
      password: Md5.hashStr('.ieieye.com' + contract.substr(-6, 6) + 'shhengji'),
      username: contract,
    };
    response = await iuserApi({
      method: 'post',
      data: {
        ...iuserOthers,
        contract,
        auth_user_w,
        company: info.company,
        type: '项目用户',
        projects: [curProject.id],
      }
    });
  } else {
    /* 编辑用户，禁止修改手机号 */
    response = await iuserById({
      method: 'patch',
      id,
      data: {
        ...iuserOthers,
      }
    })
  }
  if (!response?.id) {
    MainPopup.loading = false;
    return;
  }
  if (MainPopup.type === '新增') {
    MainApi({
      method: 'post',
      data: {
        project: curProject.id,
        space: space,
        type: MainForm.model.user_identity,
        user: response.id,
      }
    }).then(res => {
      ElMessage.success('新增成功！');
      GetMainTable();
      MainPopup.loading = false;
      MainPopup.visible = false;
    }).catch(err => {
      MainPopup.loading = false;
      MainPopup.visible = false;
    });
  } else {
    MainById({
      method: 'patch',
      id: MainForm.model.id,
      data: {
        type: MainForm.model.user_identity,
        user: response.id,
      }
    }).then(res => {
      ElMessage.success('编辑成功！');
      GetMainTable();
      MainPopup.loading = false;
      MainPopup.visible = false;
    }).catch(err => {
      MainPopup.loading = false;
      MainPopup.visible = false;
    })
  }
}

/* 新增编辑用户 */
const iuserRt = reactive({
  model: {},
  type: '',
  contract: '',
  iuser: null,
});
const handleIuserClose = () => {
  iuserRt.type = '';
  iuserRt.model = {};
}
const iuserRtRef = ref(null);
const handleIuserAdd = () => {
  iuserRt.type = '新增';
  const { user_truename, user_gender, user_identity_code } = MainForm.model;
  iuserRt.model = {
    contract: iuserRt.contract,
    truename: user_truename,
    gender: user_gender,
    identity_code: user_identity_code,
  };
}
const handleIuserChange = (value) => {
  if (!value) {
    iuserRt.type = '';
    iuserRt.iuser = null;
    iuserRt.model = {};
    return;
  }
  iuserRt.type = '编辑';
  iuserRt.iuser = MainForm.iuserList.find(i => i.id === value);
  const { id, contract, truename, gender, identity_code } = iuserRt.iuser;
  iuserRt.model = {
    id,
    contract,
    truename,
    gender,
    identity_code,
  };
}
</script>

<template>
  <div class="otherusers-box">
    <div class="flex-column mainCard">
      <el-form label-width="120px" class="flex t_form">
        <button class="go-back flex--center pointer" @click="emits('closed')">
          <el-icon size="20"><ArrowLeft /></el-icon>
          &nbsp;住户管理：{{ space_name }}
        </button>
        
        <div class="flex r_btn">
          <el-button type="primary" @click="handleMainAdd()">
            新增
          </el-button>
        </div>
      </el-form>
      <el-table :data="MainTable.data" scrollbar-always-on>
        <el-table-column label="姓名" prop="user_truename" fixed="left" min-width="140px"></el-table-column>
        <el-table-column label="性别" prop="user_gender" min-width="80px"></el-table-column>
        <el-table-column label="手机号" prop="user_contract" min-width="180px"></el-table-column>
        <el-table-column label="身份证号" prop="user_identity_code" min-width="190px"></el-table-column>
        <el-table-column label="身份" prop="type" min-width="180px"></el-table-column>
        <el-table-column label="操作" fixed="right" width="170px">
          <template #default="scope">
            <template v-if="scope.row.type !== '业主'">
              <el-button link type="primary" @click="handleMainEdit(scope.row)">
                编辑
              </el-button>
              <el-button link type="danger" @click="handleMainDelete(scope.row)">
                删除
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  
  <!-- 新增编辑 -->
  <el-dialog
    v-model="MainPopup.visible"
    :title="MainPopup.type + '住户'"
    width="600px"
    @close="handleIuserClose"
  >
    <el-form
      ref="MainFormRef"
      :model="MainForm.model"
      label-width="120px"
    >
      <template v-if="iuserRt.type !== '新增'">
        <el-form-item prop="user"  label="手机号：" :rules="[{required: true, message: '不能为空', trigger: 'change'},]">
          <el-select
            placeholder="请输入手机号"
            v-model="MainForm.model.user"
            filterable
            remote
            remote-show-suffix
            :remote-method="remoteUserMethod"
            clearable
            @change="handleIuserChange"
          >
            <el-option
              v-for="item in MainForm.iuserList"
              :key="item.id"
              :label="item.contract"
              :value="item.id"
            >
              {{ item.contract }}&nbsp;&nbsp;{{ item.truename }}
            </el-option>
            <template #empty>
              账号尚未录入，是否 
              <el-button link type="primary" @click="handleIuserAdd()">录入</el-button> ？
            </template>
            <template #footer v-if="MainForm.iuserMore">
              还有更多，请输入更精确的楼室号...
            </template>
          </el-select>
        </el-form-item>
      </template>
      <template v-if="!iuserRt.type">
        <el-form-item prop="user_truename" label="姓名：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
          <el-input v-model="MainForm.model.user_truename"></el-input>
        </el-form-item>
        <el-form-item prop="user_gender" label="性别：">
          <el-radio-group v-model="MainForm.model.user_gender">
            <el-radio label="男" value="男"></el-radio>
            <el-radio label="女" value="女"></el-radio>
            <el-radio label="空" value=""></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="user_identity_code" label="身份证号：">
          <el-input v-model="MainForm.model.user_identity_code"></el-input>
        </el-form-item>
        <el-form-item prop="user_identity" label="身份：">
          <el-radio-group v-model="MainForm.model.user_identity">
            <el-radio label="家属" value="家属"></el-radio>
            <el-radio label="租客" value="租客"></el-radio>
          </el-radio-group>
        </el-form-item>
      </template>
    </el-form>
    <el-form
      ref="iuserRtRef"
      :model="iuserRt.model"
      label-width="120px"
      v-if="iuserRt.type"
    >
      <template v-if="iuserRt.type === '新增'">
        <el-form-item prop="contract" label="手机号：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
          <el-input placeholder="请输入手机号" v-model="iuserRt.model.contract" :disabled="iuserRt.type !== '新增'"></el-input>
          <el-tooltip content="初始密码为手机号后6位" placement="right">
            <div class="description flex-center-center pointer">?</div>
          </el-tooltip>
        </el-form-item>
      </template>
      <el-form-item prop="truename" label="姓名：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
        <el-input v-model="iuserRt.model.truename"></el-input>
      </el-form-item>
      <el-form-item prop="gender" label="性别：">
        <el-radio-group v-model="iuserRt.model.gender">
          <el-radio label="男" value="男"></el-radio>
          <el-radio label="女" value="女"></el-radio>
          <el-radio label="未知" value=""></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="identity_code" label="身份证号：">
        <el-input v-model="iuserRt.model.identity_code"></el-input>
      </el-form-item>
      <el-form-item label="身份：">
        <el-radio-group v-model="MainForm.model.user_identity">
          <el-radio label="家属" value="家属"></el-radio>
          <el-radio label="租客" value="租客"></el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="MainPopup.visible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleMainSubmit()"
          v-prevent-rapid-click
          :loading="MainPopup.loading"
        >
          确 定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
@use '@T2/styles/normal.scss';
.otherusers-box {
  flex: 1;
  overflow: hidden;
  position: relative;
}
.go-back {
  background: transparent;
  border: none;
  font-weight: 600;
  font-size: 20px;
  color: #303133;
  height: 32px;
  margin-bottom: 18px;
}
.description {
  position: relative;
  width: 20px;
  height: 20px;
  background-color: #888888;
  border-radius: 50%;
  color: #ffffff;
  margin-left: 5px;
}
</style>